package filereaders;

import java.util.HashMap;
import java.util.Map;


/**
 * 
 * @author Paul Dannenberg
 * 
 */

// TODO Error handling if filetype is unsupported.

public class ParserFactory {

    private static final String FILE_EXTENSION_DELIMETER = ".";

    /**
     * Normal file extension length includes the period. e.g. the extension
     * length of file.txt would be 4, the length of ".txt".
     */
    private static final int NORMAL_FILE_EXTENSION_LENGTH = 4;

    private Map<String, Parser> myParsers;

    /*
     * Add any new file type extensions that can now be
     * parsed in this method.
     */
    private void fillFileExtensionOptions(String filename) {
        myParsers = new HashMap<String, Parser>();
        myParsers.put(".txt", new TxtParser(filename));
    }

    /**
     * Returns the correct Parser depending on the filename's
     * file extension.
     * 
     * @param filename The file to create a parser for.
     * @return An object that is capable of parsing data from
     *         the file specified as the filename argument.
     */
    public Parser createParser(String filename) {
        fillFileExtensionOptions(filename);
        return myParsers.get(getFileExtension(filename));
    }

    private String getFileExtension(String filename) {
        int delimeterIndex = filename.length() - NORMAL_FILE_EXTENSION_LENGTH;
        for (int i = 0; i < filename.length(); i++) {
            if (FILE_EXTENSION_DELIMETER.equals(filename.charAt(i))) {
                delimeterIndex = i;
            }
        }
        return filename.substring(delimeterIndex);
    }
}
